<template>
  <view>
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <loading :showLoaded.sync="showLoaded"></loading>
    <view class="pay_success">
      <view class="pay_success_top">
        <image style="width: 20%;" mode="widthFix"
          src="https://100000063-1252208446.cos.ap-shanghai.myqcloud.com/images/miniprogram/submitSuccess.jpg" />
        <p class="pay_success_top_p1">预约成功</p>
      </view>
      <p class="pay_success_text">
        小程序系统将对您的申请进行审核，如审核通过，您将获取相关商品的购买资格。
      </p>
      <p class="pay_success_text2">
        温馨提示：预约并非下单。如经系统审核，该预约申请存在异常或预约商品出现库存不足等情形时，则预约申请可能不成功，从而不能进入下单环节。相关政策详见<text
          @click.stop="shoppingInstructions" class="check-dec">《THE MACALLAN麦卡伦线上精品店购物须知》</text>或咨询在线客服。
      </p>
      <view class="purchase">
        <view class="">
          <view class="purchaseTop">
            <view class="purchaseTop-left">
              <p class="purchaseTop-p">预约申请编号</p>
              <p class="content">{{'Y' + obj.orderCode}}</p>
            </view>
            <view class="purchaseTop-right">
              <p class="purchaseTop-p">状态</p>
              <p class="content content3">
                {{obj.approveStatus == 0 ? '待审核' : obj.approveStatus == 1 ? '待支付' : obj.approveStatus == -1 ? '已关闭' : orderStatusList[obj.status]}}
              </p>
            </view>
          </view>
          <block v-for="(item, index) in obj.items" :key="index" v-if="item.isGift == 0">
            <view class="purchaseGoods">
              <image class="purchaseGoods-img" :src="item.skuImageUrl" mode="widthFix"></image>
              <view class="purchaseGoods-top">
                <p class="purchaseGoods-p">{{item.itemName}}</p>
                <view class="purchaseGoods-bottom">
                  <p class="price">容量: {{ item.skuProperties[0].valueName }}</p>
                  <p class="goods_num">x {{item.qty}}</p>
                </view>
              </view>
            </view>
          </block>
        </view>
        <view class="total">
          <p class="total-p" v-if="!!obj.notGiftTotalNum">共{{obj.notGiftTotalNum}}件商品，合计：<text
              class="text2">¥</text><span class="total-span">{{filterChecked.moneyFormat(obj.payment, 2)}}</span></p>
          <view class="button">
            <button type="" class="button1" @click="goIndex">返回首页</button>
            <button type="" class="button1" @click="goOrderDetail">查看预约申请</button>
          </view>
        </view>
      </view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>
<script module="filterChecked" lang="wxs" src="../../utils/filter.wxs"></script>
<script>
  import api from '@/api/api';
  import Loading from '../../components/common/loading';
  import NavBar from '../../components/common/navbar';
  import {
    SYSTEM_INFO,
    CUSTOMER_INFO,
    CART_KEY
  } from '@/utils/constant';
  import tip from '@/utils/tip';
  export default {
    config: {
      navigationStyle: 'custom',
      navigationBarTitleText: '预约成功'
    },
    components: {
      loading: Loading,
      navBar: NavBar
    },
    data() {
      return {
        showLoaded: true,
        orderList: [],
        obj: {},
        isShowCustomNavBar: true,
        // 组件所需的参数
        navbarData: {
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          navbarTitle: '预约成功', //导航栏 中间的标题
          hideSearch: true,
          hideHome: false
        },
        orderNo: '',
        jwt: '',
        payment: 0, //价格
        previousPages: '',
        status: '', //状态
        orderCode: '', //订单编号
        itemName: '', //商品名
        qty: 0, //数量
        skuImageUrl: '', //商品图片地址
        // skuProperties:{},
        ren: {},
        value: {},
        nowPages: '',
        orderStatusList: {
          WAIT_BUYER_PAY: '待支付',
          BUYER_PART_PAYMENT: '继续支付',
          WAIT_SELLER_SEND_GOODS: '待审核',
          WAIT_BUYER_CONFIRM_GOODS: '待收货',
          TRADE_FINISHED: '已完成',
          TRADE_CLOSED: '已取消',
          TRADE_CLOSED_BY_CLOUD: '已关闭',
          RETAIL_STORE_RECEIVED: '门店已收货',
          DC_RECEIVED: '仓库已收货'
        }
      };
    },

    onLoad(option) {
      this.showLoaded = true;
      this.orderNo = option.orderNo;
      this.getOrderInfo();
      this.getCustomerCart();
      this.validateCart();
      let pages = getCurrentPages();
      let prevpage = pages[pages.length - 2];
      var currPage = pages[pages.length - 1];
      this.nowPages = currPage.route;
    },
    onShow() {
      getApp().cl_tracker.track('mini_program_view', {
        path: this.nowPages,
        pageName: '预约成功',
      })
    },
    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      // 根据订单号查询详情
      getOrderInfo: async function() {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
        //判断是否可以确认收货 0 - 不可以， 1- 可以
        const ConfirmJudge = await api.isAllowConfirm({
            header: {
              jwt: customerInfo.jwt
            }
          },
          this.orderNo
        );
        if (ConfirmJudge.code == 1000) {
          this.isAllowConfirm = ConfirmJudge.data.isAllow;
        }

        //判断是否可以申请退货 0 - 不可以， 1- 可以
        const applyJudge = await api.isAllowapplyRefund({
            header: {
              jwt: customerInfo.jwt
            }
          },
          this.orderNo
        );
        if (applyJudge.code == 1000) {
          this.isAllowApplyRefund = applyJudge.data.isAllow;
        }

        const json = await api.getOrderInfo({
            header: {
              jwt: customerInfo.jwt
            }
          },
          this.orderNo
        );
        if (json.code === 1000) {
          this.obj = json.data;
          let notGiftNum = 0
          let notGiftTotalNum = 0
          this.obj.items.forEach(innerItem => {
            if (innerItem.isGift == 0) {
              notGiftNum++
			  notGiftTotalNum += innerItem.qty
            }
          });
          this.obj.notGiftNum = notGiftNum
		  this.obj.notGiftTotalNum = notGiftTotalNum
          that.orderSource = this.obj.orderSource;
          that.payType = this.obj.payType;
          that.list = json.data.items;
          that.showLoaded = false;
          let orderItemIdArr = [];
          let discountsArr = [];
          //解析每个数组下面的items.skuProperties属性
          that.list.forEach(function(item, index, array) {
            that.list[index].skuProperties = JSON.parse(array[index].skuProperties);
            // 赠品名称
            if (that.list[index].isGift == 1) {
              that.giftName = that.list[index].itemName;
            }
            // 促销
            if (that.list[index].discounts && that.list[index].discounts.length > 0) {
              for (let j = 0; j < that.list[index].discounts.length; j++) {
                if (discountsArr.indexOf(that.list[index].discounts[j].discountName) == -1) {
                  discountsArr.push(that.list[index].discounts[j].discountName);
                }
              }
            }

            if (orderItemIdArr.indexOf(that.list[index].orderItemId) == -1) {
              orderItemIdArr.push({
                num: that.list[index].qty,
                orderItemId: that.list[index].orderItemId,
                reason: '未发货取消订单'
              });
            }
          });

          that.discountsArr = discountsArr;
          if (that.discountsArr && that.discountsArr.length == 1) {
            that.discountsArr[0].indexOf('运费') !== -1
            that.onlyFreight = true
          } else {
            that.onlyFreight = false
          }
          that.refundItems = orderItemIdArr;
          that.itemLength = that.list.length;
          that.showLoaded = false;
        } else {
          that.showLoaded = false;
          that.handleShowTextToast(json.data.msg);
        }
      },
      getPayOrderDetail: async function() {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
        const json = await api.getOrderInfo({
            header: {
              jwt: customerInfo.jwt
            }
          },
          this.orderNo
        );

        if (json.code === 1000) {
          that.orderList = json.data.items;
          that.obj = json.data;
          let notGiftNum = 0
          let notGiftTotalNum = 0
          that.obj.items.forEach(innerItem => {
            if (innerItem.isGift == 0) {
              notGiftNum++
              notGiftTotalNum += innerItem.qty
            }
          });
          that.obj.notGiftNum = notGiftNum
          that.obj.notGiftTotalNum = notGiftTotalNum
          //解析每个数组下面的items.skuProperties属性
          that.orderList.forEach(function(item, index, array) {
            that.orderList[index].skuProperties = JSON.parse(array[index].skuProperties);
          })
          that.ren = json.data.items[0];
          that.value = JSON.parse(json.data.items[0].skuProperties);
          that.$EFSTracking.trackingOrder('PAY_SUCCESS', orders.orderId,
            orders.items, orders.payment, orders.postFee, orders.discountFee, orders.itemTotal);
          that.payment = json.data.payment;
          that.status = json.data.status;
          that.orderCode = json.data.orderCode;
          that.itemName = json.data.items.itemName;
          that.qty = json.data.items.qty;
          tip.loaded()
        } else {
          tip.loaded()
          that.handleShowTextToast(json.msg);
        }
      },
      validateCart: async function() {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        //查询一次购物车 如果报错，则重新加载cartKey
        this.$commonFunction.getCartList().then((res) => {
        }).catch((err) => {
          uni.setStorageSync(CART_KEY, null);
        });
      },

      getCustomerCart: async function() {
        let that = this;
        let cart_key = uni.getStorageSync(CART_KEY);
        let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
        if (jwt && cart_key !== null) {
          that.$commonFunction.getCartList().then((res) => {
            if (res && res.items !== null) {
              that.$store.commit('changeCartNum', res.availableTotalQty);
            }
          }).catch((err) => {
            that.handleShowTextToast(err.msg);
          });
        }
      },
      // 购物须知
      shoppingInstructions() {
        uni.navigateTo({
          url: '/pages/cms/page?identifier=cms/shoppingInstructions&name=购物须知'
        })
      },
      goOrderDetail() {
        uni.navigateTo({
          url: '/pages/order/list'
        });
      },
      goIndex() {
        uni.reLaunch({
          url: '/pages/home/home',
          success: function(e) {
            var page = getCurrentPages().pop();
            if (page == undefined || page == null) return;
            page.onLoad();
          }
        });
      },
    }
  };
</script>
<style lang="less">
  .pay_success_top_p1 {
    font-size: 36rpx;
  }

  .pay_success {
    background: #fff;
    margin: 0 46rpx;

    .pay_btn,
    .pay_type,
    .pay_money {
      display: flex;
      width: 100%;
    }

    .icon {
      margin: 0 auto;
      text-align: center;
      padding-top: 100rpx;
    }

    .block {
      margin: 0 auto;
      text-align: center;
      display: flex;
      align-items: center;
    }

    .icon-success {
      color: #ea4a3a;
      font-size: 150rpx;
    }

    .success_doc {
      color: #1a1a1a;
    }

    .type {
      color: #ea4a3a;
    }

    .pay_type {
      padding-top: 14rpx;
    }

    .pay_money {
      padding-top: 25rpx;
    }

    .btn_group {
      display: flex;
      align-items: center;
      padding-top: 160rpx;

      .btn {
        font-size: 30rpx;
        padding: 10rpx 55rpx;
        text-align: center;
        margin: 0 auto;
        width: 100%;
      }

      .order_detail {
        color: #333;
        border: 1px solid #ccc;
      }

      .get_store {
        background: #ed601b;
        color: #fff;
        margin-left: 85rpx;
      }
    }
  }

  .pay_success_top {
    margin: 50px 10px 30rpx 10px;
    text-align: center;
  }

  .purchase {
    border: 1px solid #e7e7e7;
  }

  .purchaseTop {
    margin: 25rpx 22rpx;
    background: #fff;
    border-bottom: 1px solid #e7e7e7;
    padding-bottom: 11rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .content {
      color: #1b1b1b;
      font-size: 24rpx;
    }

    .content3 {
      color: #862633 !important;
    }
  }

  .purchaseTop-left {}

  .purchaseTop-right {
    text-align: right;
  }

  .purchaseGoods {
    display: flex;
    position: relative;
    padding: 0 15rpx 24rpx 15rpx;
    margin: 20rpx 9rpx 0;
  }

  .purchaseGoods-img {
    width: 120rpx;
  }

  .purchaseGoods-bottom {
    display: flex;
    justify-content: space-between;
  }

  .purchaseGoods-p {
    font-size: 28rpx;
    color: #1b1b1b;
    margin-bottom: 10rpx;
    padding: 0;
    line-height: 40rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2; // 控制多行的行数
    -webkit-box-orient: vertical;
  }

  .purchaseGoods-top {
    margin-left: 40rpx;
    width: 70%;
  }

  .total {
    margin-top: 10px;
    padding: 0rpx 30rpx 30rpx;
  }

  .total-p {
    font-size: 28rpx;
    color: #1b1b1b;
    text-align: right;
  }

  .total-span {
    font-size: 32rpx;
    color: #1b1b1b;
  }

  .button {
    margin-top: 20rpx;
    text-align: right;
  }

  .button1 {
    color: #1B1B1B;
    min-width: 35%;
    margin: 0 auto;
    border: 1px solid #a0a0a0;
    height: 39px;
    line-height: 39px;
    display: inline-block;
    margin-bottom: 10px;
    background-color: #fff;
    text-align: center;
    margin-left: 20rpx;
  }

  .button2 {
    display: inline-block;
  }

  .purchaseTop-p {
    font-size: 24rpx;
    display: block;
    color: #b0b0b0;
  }

  .pay_success_text {
    margin: 0px 10px 30rpx;
    margin-bottom: 0;
    text-indent: 50rpx;
  }

  .pay_success_text2 {
    margin: 0px 10px 30rpx;
    text-indent: 50rpx;
  }

  .text2 {
    font-size: 28rpx;
    margin-right: 2rpx;
  }

  .check-dec {
    text-decoration: underline;
    margin-bottom: 4rpx;
  }

  .price,
  .goods_num {
    font-size: 28rpx;
    font-weight: 400;
    color: #b0b0b0;
  }
</style>
